package com.dzy.chiyan.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import com.dzy.chiyan.activity.ChatActivity
import com.dzy.chiyan.R
import java.text.SimpleDateFormat
import java.util.*

// 处理与聊天相关的操作
class ChatAdapter(private val chatList: MutableList<Chat>,val userID: Int) : RecyclerView.Adapter<ChatAdapter.ChatViewHolder>() {
    private lateinit var context: Context
    // 保存视图中的UI组件
    class ChatViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val nicknameTextView: TextView = itemView.findViewById(R.id.nicknameTextView)
        val messageTextView: TextView = itemView.findViewById(R.id.messageTextView)
        val timeTextView: TextView = itemView.findViewById(R.id.timeTextView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
        context = parent.context
        val view = LayoutInflater.from(context).inflate(R.layout.item_chat, parent, false)
        return ChatViewHolder(view)
    }

    override fun onBindViewHolder(holder: ChatViewHolder, position: Int) {
        val chat = chatList[position]
        // 设置聊天昵称、最新消息和时间
        holder.nicknameTextView.text = chat.name
        holder.messageTextView.text = chat.message
        holder.timeTextView.text = convertUnixTimestampToString(chat.time)
        // 跳转到聊天详情界面
        holder.itemView.setOnClickListener {
            val intent = Intent(context, ChatActivity::class.java)
            intent.putExtra("friendId", chat.friendId)
            intent.putExtra("userID", userID)
            context.startActivity(intent)
        }
        // 长按事件，显示删除聊天确认对话框
        holder.itemView.setOnLongClickListener {
            showDeleteConfirmationDialog(holder.adapterPosition)
            true
        }
    }

    private fun convertUnixTimestampToString(unixTimestamp: String): String {
        return try {
            val timestampLong = unixTimestamp.toLong() * 1000
            val date = Date(timestampLong)
            val currentDate = Date()

            val isSameDay = date.year == currentDate.year &&
                            date.month == currentDate.month &&
                            date.date == currentDate.date

            val dateFormat = if (isSameDay) {
                SimpleDateFormat("HH:mm", Locale.getDefault())
            } else {
                SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
            }

            dateFormat.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    override fun getItemCount(): Int = chatList.size

    private fun showDeleteConfirmationDialog(position: Int) {
        val alertDialog = AlertDialog.Builder(context)
            .setTitle("删除对话")
            .setMessage("您确定要删除该对话吗？")
            .setPositiveButton("确定") { dialog, which ->
                chatList.removeAt(position)
                notifyItemRemoved(position)
            }
            .setNegativeButton("取消", null)
            .create()

        alertDialog.show()
    }
    // 新聊天
    fun addChat(chat: Chat) {
        chatList.add(chat)
        notifyItemInserted(chatList.size - 1)
    }
    // 重新加载聊天列表数据
    fun reloadData(newFriendList: List<Chat>) {
        chatList.clear()
        chatList.addAll(newFriendList)
        notifyDataSetChanged()
    }

}
